package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"user-mgmt-sys/handler"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
func Init() *gin.Engine {
	r := gin.Default()
	r.Use(Cors())
	r.Static("/static", "./static")
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})
	r.POST("/login", handler.Login)
	r.POST("/userrole", handler.UserRole)
	r.POST("/roleNode", handler.RoleNode)
	r.GET("/user", handler.User)
	r.GET("/usernode", handler.UserNode)
	r.GET("/role", handler.Role)
	r.GET("/detail", handler.Detail)
	r.POST("/add", handler.Add)
	r.POST("/chen/chenlogin", handler.ChenLogin)
	r.POST("/chen/chenrolenode", handler.ChenRoleNode)
	r.GET("/chen/chenuserrole", handler.ChenUserRole)
	r.GET("/chen/chenrolenodes", handler.ChenRoleNodes)
	r.POST("/chen", handler.Chen)
	r.POST("/chenAdd", handler.ChenAdd)
	r.GET("/chenList", handler.ChenList)
	r.GET("/chenDetail", handler.ChenDetail)
	return r
}
